import pathlib
import time
import re
import typing
import os
import yaml
import ctypes
import psutil
import subprocess
import requests
import winsound
import datetime
import rich
from selenium.webdriver.edge.webdriver import WebDriver
from selenium.webdriver.edge.service import Service
from selenium.webdriver.edge.options import Options
from selenium.webdriver.remote.webelement import WebElement
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.common.exceptions import *



def print_with_time(*args, **kwargs):
    """在输出内容前添加当前时间戳，使用rich.print进行格式化输出
    
    功能：在所有输出内容前自动添加当前本地时间，时间格式为YYYY-MM-DD HH:MM:SS
    时间会以蓝色加粗样式显示，其余内容保持rich的默认格式化特性
    
    Args:
        *args: 任意数量的位置参数，将被原样传递给rich.print
        **kwargs: 任意关键字参数，将被原样传递给rich.print
    
    Example:
        >>> print_with_time("系统启动完成")
        [bold blue][2025-08-07 16:45:30][/bold blue] 系统启动完成
        
        >>> print_with_time("操作结果：", "[green]成功[/green]")
        [bold blue][2025-08-07 16:46:10][/bold blue] 操作结果：[green]成功[/green]
    """
    # 获取当前时间并格式化为字符串
    current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    # 拼接时间前缀与输出内容并打印
    rich.print(f"[bold blue][{current_time}][/bold blue]", *args, **kwargs)







def On_SelectPage_Select_FirstCategory(driver:WebDriver,Cate_Name:str):
    """选择第一个类目

    Args:
        driver (WebDriver): WebDriver 实例
        Cate_Name (str): 类目名称
    """
        # 选择一级类目
    try:
        xpath_value = f"//ul/li//div[text()='{Cate_Name}']"
        element  = driver.find_element(by=By.XPATH,value=xpath_value)
        driver.execute_script("arguments[0].click();",element)
        
        # 验证是否出现指定的 xpath 元素
        try:
            verify_xpath = f"//ul/li//div[text()='T恤']"
            WebDriverWait(driver=driver,timeout=10).until(expected_conditions.presence_of_element_located((By.XPATH,verify_xpath)))
        except TimeoutException:
            print_with_time(f"[red]提示 : 一级类目加载超时,请检查类目是否正确![/red]")

    except NoSuchElementException:
        print_with_time("[red]提示 : 一级类目不存在,请检查类目是否正确![/red]")
        




def On_SelectPage_Select_SecondCategory(driver:WebDriver,Cate_Name:str):
    """选择第二个类目

    Args:
        driver (WebDriver): WebDriver 实例
        Cate_Name (str): 类目名称
    """
    try:
        xpath_value = f"//ul/li//div[text()='{Cate_Name}']"
        element  = driver.find_element(by=By.XPATH,value=xpath_value)
        driver.execute_script("arguments[0].click();",element)
        
        try:
            verify_xpath = f"//ul/li[contains(@class,'selected')]//div[text()='{Cate_Name}']"
            WebDriverWait(driver=driver,timeout=10).until(expected_conditions.presence_of_element_located((By.XPATH,verify_xpath)))
        except TimeoutException:
            print_with_time(f"[red]提示 : 二级类目加载超时,请检查类目是否正确![/red]")

    except NoSuchElementException:
        print_with_time("[red]提示 : 二级类目不存在,请检查类目是否正确![/red]")



def On_SelectPage_Select_CatePro(driver:WebDriver,CatePro:str):
    """在类目选择页面中选择品牌

    Args:
        driver (WebDriver): WebDriver 实例
        Cate_Name (str): 品牌名称
    """
    pass
        



def Goto_Parameter_Input(driver:WebDriver,Delay:float=5):
    """进入到参数填写页面.

    Args:
        driver (WebDriver): WebDriver 实例
        Delay (float, optional): 函数延时参数. Defaults to 5.
    """
    wait_start_time = datetime.datetime.now()
    while wait_start_time + datetime.timedelta(seconds=10) > datetime.datetime.now():
        try:
            xpath_value = f"//button/span[text()='确认发布该类商品']"
            element  = driver.find_element(by=By.XPATH,value=xpath_value)
            driver.execute_script("arguments[0].click();",element)
            time.sleep(0.2)
        except NoSuchElementException:
            print_with_time("[red]提示 : 类目选择成功![/red]")
            break
    time.sleep(5)
    
    
    
    
    
        
if __name__ == "__main__":
    options = Options()
    options.add_experimental_option("debuggerAddress", "127.0.0.1:9652")
    service = Service()
    driver = WebDriver(options=options, service=service)
    debug_json_data = requests.get(
        url="http://127.0.0.1:9652/json", timeout=5).json()

    # 判断获取回来的数据是否正确
    if not isinstance(debug_json_data, list):
        print_with_time("接口返回数据格式不正确（非列表或为空）")
        exit(0)

    # 过来掉不需要的 page 页面
    filter_json_data = list(
                                    filter(lambda item: (
                                        item['type'] == "page" and
                                        not item['title'].lower().startswith("devtools") and
                                        not item['title'].lower().startswith("offscreen") and
                                        not item['title'].lower().startswith("新标签页") and
                                        not item['url'].lower().startswith("edge://newtab/") and
                                        not item['url'].lower().startswith("chrome-extension") and
                                        not item['url'].lower().startswith("chrome-devtools")
                                    ), debug_json_data)
                                )
    current_activate_handle = filter_json_data[0]['id']
    driver.switch_to.window(current_activate_handle)